<?php


namespace App\Models\CacheModel;


use App\Models\CacheModel\zlcr2\Zlcr2UserQuestion;
use app\common\lib\exception\ApiException;
use App\Models\Api\BaseCache;
use think\Cache;
use AstroTool\Cache\CacheManage;

class ArticleCommentGood extends BaseCache
{
    protected $table = 'wechatadmin.system_comment_good';
    protected $cacheModel = 'content.comment_good';

    /**
     * 添加点赞
     * @param array $userInfo
     * @param int $id 评论id /  回复id
     * @param array $data
     * @param int $type 1=>评论，2=》回复
     * @return bool
     */
    public function saveData(array $userInfo, int $id, array $data, int $type)
    {
        try
        {
            $articleCommentModel = new ArticleComment();
            switch ($type)
            {
                case 1:
                    //获取评论详情
                    $info = current($articleCommentModel->batchGetInfo([$id], ['goods', 'type', 'aid', 'uid', 'reply']));
                    if ((int)$info['type'] === 4)
                    {
                        $qInfo = (new Zlcr2UserQuestion())->getInfoById($info['aid'], ['delete_time']);
                        if($qInfo['delete_time'] > 0){
                            throw new ApiException('当前问题评论已禁止点赞');
                        }
                    }
                    $info['goods']++;
                    $updateReply = ['goods' => $info['goods']];
                    //更新评论点赞数
                    $articleCommentModel->where('id', $id)->update($updateReply);
                    CacheManage::getInstance()->setCacheConfig('content.comment', $id)->setCache($updateReply);
                    if ($info['type'] == 3)
                    {
                        //更新话题详情缓存，插入点赞操作一百的评论
                        $theme = CacheManage::getInstance()->setCacheConfig('goddess_area.theme', $info['aid'])->getCache(['goddess_reply_id', 'reply_good_max_num', 'reply_avatars']);
                        //若话题详情缓存存在且当前评论点赞数超100         并且没有女神回复          若当前评论点赞数超过缓存中的评论点赞数，则替换缓存的评论信息
                        if ($theme && $info['goods'] >= 100 && !$theme['goddess_reply_id'] && $info['goods'] > $theme['reply_good_max_num'])
                        {
                            CacheManage::getInstance()->setCacheConfig('goddess_area.theme', $info['aid'])->setCache(['good_max_comment_id' => $id, 'reply_good_max_num' => $info['goods']]);
                        }
                        if ($theme && $userInfo['avatar'])
                        {   // 互动头像添加
                            (new GoddessArea())->interactionAvatars($info['aid'], $userInfo['avatar'], $theme);
                        }
                    }

                    if ($info['type'] == 4)
                    {
                        $articleCommentModel->setCommentAndGoodSum($info['aid'], $id, $info['goods'] + $info['reply']);
                    }
                    break;
                case 2:
                    //获取评回复详情
                    $articleCommentReplyModel = new ArticleCommentReply();
                    $info = $articleCommentReplyModel->getInfoById($id, ['good_num', 'type', 'aid', 'uid1']);
                    if ((int)$info['type'] === 4)
                    {
                        $qInfo = (new Zlcr2UserQuestion())->getInfoById($info['aid'], ['delete_time']);
                        if($qInfo['delete_time'] > 0){
                            throw new ApiException('当前问题评论已禁止点赞');
                        }
                    }
                    $info['uid'] = $info['uid1'];
                    $info['good_num']++;
                    $updateReply = ['good_num' => $info['good_num'] < 0 ? 0 : $info['good_num']];
                    //更新评论点赞数
                    $articleCommentReplyModel->where('id', $id)->update($updateReply);
                    CacheManage::getInstance()->setCacheConfig('content.reply', $id)->setCache($updateReply);
                    if ($info['type'] == 3 && $userInfo['avatar'])
                    {
                        $theme = CacheManage::getInstance()->setCacheConfig('goddess_area.theme', $info['aid'])->getCache(['id', 'reply_avatars']);
                        if ($theme)
                        {
                            (new GoddessArea())->interactionAvatars($info['aid'], $userInfo['avatar'], $theme);
                        }
                    }
                    break;
                default:
                    return false;
                    break;
            }
            if ($info)
            {
                //设置被点赞用户未读状态缓存
                Cache::inc('user_good_unread_status_' . $info['uid'], 1);
                //删除评论点赞中间表数据
                $data['aid'] = $info['aid'];
                $data['uid2'] = $info['uid'];
                $data['article_type'] = $info['type'];
                $insertId = $this->insertGetId($data);
                //更新用户点赞相关列表
                $this->listDataAdd((int)$userInfo['id'] . '-0-' . $type, [$insertId => $insertId], 1);
                $this->listDataAdd((int)$userInfo['id'] . '-' . $info['type'] . '-' . $type, [$insertId => $insertId], 1);
                $this->listDataAdd((int)$userInfo['id'] . '-' . $info['type'] . '-0', [$insertId => $insertId], 1);
                $this->listDataAdd((int)$info['uid'] . '-0-' . $type, [$insertId => $insertId], 2);
                $this->listDataAdd((int)$info['uid'] . '-' . $info['type'] . '-' . $type, [$insertId => $insertId], 2);
                $this->listDataAdd((int)$info['uid'] . '-' . $info['type'] . '-0', [$insertId => $insertId], 2);
                $this->listDataAdd((int)$info['uid'] . '-0-0', [$insertId => $insertId], 2);
                $cacheKey = $info['type'] == 1 ? 'good' : 'good_num';
                //对应内容点赞数据自增 1
                (new ArticleComment())->commentOrgoodAdd($info['type'], $info['aid'], $cacheKey, 1);
            }
        }
        catch (\Exception $e)
        {
            return false;
        }
        return true;
    }

    /**
     * 批量删除点赞记录
     * @param $ids
     * @return bool
     */
    public function updateData($ids)
    {
        try
        {
            $data = $this->batchGetInfoByIds($ids, ['type', 'comment_id', 'article_type', 'id', 'uid2']);
            $this->where(['id' => ['in', $ids]])->update(['is_hide' => 1]);
            foreach ($data as $datum)
            {
                //隐藏评论点赞记录
                $this->listDataDel($datum['uid2'] . '-0-' . $datum['type'], [$datum['id']], 2);
                $this->listDataDel($datum['uid2'] . '-' . $datum['article_type'] . '-' . $datum['type'], [$datum['id']], 2);
                $this->listDataDel($datum['uid2'] . '-' . $datum['article_type'] . '-0', [$datum['id']], 2);
                $this->listDataDel($datum['uid2'] . '-0-0', [$datum['id']], 2);
                CacheManage::getInstance()->setCacheConfig($this->cacheModel, $datum['id'])->rmCache();
            }
        }
        catch (\Exception $e)
        {
            return false;
        }
        return true;
    }

    /**
     * 取消点赞
     * @param int $uid
     * @param int $id 评论id / 回复id
     * @param array $where
     * @param int $type 1=>评论，2=》回复
     * @return bool
     */
    public function delData(int $uid, int $id, array $where, int $type)
    {
        try
        {
            $articleCommentModel = new ArticleComment();
            switch ($type)
            {
                case 1:
                    //获取评论详情
                    $info = current($articleCommentModel->batchGetInfo([$id], ['type', 'goods', 'aid', 'uid', 'reply']));
                    $info['goods']--;
                    $updateReply = ['goods' => $info['goods']];
                    $cakey = 'content.comment';
                    //更新评论点赞数
                    $articleCommentModel->where('id', $id)->update($updateReply);
                    CacheManage::getInstance()->setCacheConfig($cakey, $id)->setCache($updateReply);
                    if ($info['type'] == 4)
                    {
                        $articleCommentModel->setCommentAndGoodSum($info['aid'], $id, $info['goods'] + $info['reply']);
                    }
                    break;
                case 2:
                    //获取评回复详情
                    $articleCommentReplyModel = new ArticleCommentReply();
                    $info = $articleCommentReplyModel->getInfoById($id, ['good_num', 'type', 'aid', 'uid1']);
                    $info['uid'] = $info['uid1'];
                    $info['good_num']--;
                    $updateReply = ['good_num' => $info['good_num'] < 0 ? 0 : $info['good_num']];
                    $cakey = 'content.reply';
                    //更新回复点赞数
                    $articleCommentReplyModel->where('id', $id)->update($updateReply);
                    CacheManage::getInstance()->setCacheConfig($cakey, $id)->setCache($updateReply);
                    break;
                default:
                    return false;
                    break;
            }
            if ($info)
            {
                //删除评论点赞中间表数据
                $data = $this->where($where)->field('id')->find();
                $this->where($where)->delete();
                $this->listDataDel($uid . '-0-' . $type, [$data['id']], 1);
                $this->listDataDel($uid . '-' . $info['type'] . '-' . $type, [$data['id']], 1);
                $this->listDataDel($uid . '-' . $info['type'] . '-0', [$data['id']], 1);
                $this->listDataDel($info['uid'] . '-0-' . $type, [$data['id']], 2);
                $this->listDataDel($info['uid'] . '-' . $info['type'] . '-' . $type, [$data['id']], 2);
                $this->listDataDel($info['uid'] . '-' . $info['type'] . '-0', [$data['id']], 2);
                CacheManage::getInstance()->setCacheConfig($this->cacheModel, $data['id'])->rmCache();
                $cacheKey = $info['type'] == 1 ? 'good' : 'good_num';
                //对应内容点赞数据自增 1
                (new ArticleComment())->commentOrgoodAdd($info['type'], $info['aid'], $cacheKey, -1);
            }
        }
        catch (\Exception $e)
        {
            return false;
        }
        return true;
    }

    /**
     * 获取用户点赞记录list
     * @param int $uid
     * @param int $type 类型 [0=>全部,1=>评论，2=》回复]
     * @param int $articleType 0=>全部 1=>星文，2=>女神动态，3=>女神专区 4=>问答 5=>星座讨论
     * @param int $listType 1=>用户点赞集合  2=>用户被点赞集合
     * @return array
     * @throws \Exception
     */
    public function getGoodIds(int $uid, int $type, int $articleType = 0, int $listType = 1)
    {
        return CacheManage::getInstance()->setCacheConfig($this->cacheModel, $uid . '-' . $articleType . '-' . $type)->setListKeyType($listType)->setSort('DESC')->ZsGetIocData('list', function () use ($uid, $type, $articleType, $listType)
        {
            try
            {
                $where = [];
                if ($listType === 1)//用户点赞
                {
                    $where ['uid'] = $uid;
                } else//用户被点赞
                {
                    $where['uid2'] = $uid;
                    $where['is_hide'] = 0;
                }
                if ($type)
                {
                    $where['type'] = $type;
                }
                if ($articleType)
                {
                    $where['article_type'] = $articleType;
                }
                $comment_ids = $this->where($where)->order('id', 'DESC')->column('id', 'id');
                $comment_ids = keyValue($comment_ids);
            }
            catch (\Exception $e)
            {
                $comment_ids = [];
            }
            return $comment_ids;
        });
    }

    /**
     * 获取用户点赞的id集合，用于判断是否点赞
     * @param int $uid
     * @param int $type 类型 [0=>全部,1=>评论，2=》回复]
     * @param int $articleType 0=>全部 1=>星文，2=>女神动态，3=>女神专区 4=>问答
     * @param int $listType 1=>用户点赞集合  2=>用户被点赞集合
     * @return array
     * @throws \Exception
     */
    public function getGoodFromCache(int $uid, int $type, int $articleType = 0, int $listType = 1)
    {
        $ids = $this->getGoodIds($uid, $type, $articleType, $listType);
        return array_column($this->batchGetInfoByIds($ids, ['comment_id']), 'comment_id');
    }

    /**
     * 批量获取数据
     * @param $ids
     * @param $type
     * @param $sortType
     * @return array|false|string|void
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        try
        {
            $data = $this->where(['id' => ['in', $ids]])->column('aid,comment_id,article_type,create_time,uid,uid2,type', 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }
}
